package fr.afcepf.ai89.esharing.data;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.afcepf.ai89.esharing.entity.Aem;
import fr.afcepf.ai89.esharing.entity.InvisibiliteAem;

@Stateless
public class DAOInvisibiliteAem implements IDAOInvisibiliteAem {

	@PersistenceContext(unitName = "ESharingPhase22")
	EntityManager em;
	
	@Override
	public InvisibiliteAem getInvisAem(int idInvisAem) {
		Query hql = em.createQuery("SELECT inv FROM InvisibiliteAem inv WHERE inv.idInvisibiliteAem = :idInv");
		hql.setParameter("idInv", idInvisAem);
		return (InvisibiliteAem) hql.getSingleResult();
	}

	@Override
	public List<InvisibiliteAem> getInvisAem() {
		Query hql = em.createQuery("SELECT inv FROM InvisibiliteAem");
		return hql.getResultList();
	}

	@Override
	public List<InvisibiliteAem> getInvisAem(Aem aem) {
		Query hql = em.createQuery("SELECT inv FROM InvisibiliteAem inv WHERE inv.aem = :aem");
		hql.setParameter("aem", aem);
		return hql.getResultList();
	}

	@Override
	public int addInvisAem(InvisibiliteAem invisAem) {
		em.persist(invisAem);
		
		Query hql = em.createQuery("SELECT MAX(idInvisibiliteAem) FROM InvisibiliteAem inv");
		int idInvis = (Integer)hql.getSingleResult();
		
		return idInvis;
	}

	@Override
	public int majInvisAem(InvisibiliteAem invisAem) {
		
		InvisibiliteAem newInvis = em.find(InvisibiliteAem.class, invisAem.getIdInvisibiliteAem());
		
		newInvis.setDebutInvisibiliteAem(invisAem.getDebutInvisibiliteAem());
		newInvis.setFinInvisibiliteAem(invisAem.getFinInvisibiliteAem());
		
		em.merge(newInvis);
		return newInvis.getIdInvisibiliteAem();
		
	}

	@Override
	public int retirerInvisAem(InvisibiliteAem invisAem) {
		invisAem = em.find(InvisibiliteAem.class, invisAem.getIdInvisibiliteAem());
		invisAem.setRetraitInvisibiliteAem(new Date());
		em.merge(invisAem);
		return invisAem.getIdInvisibiliteAem();
	}

}
